import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', {
  // 状态
  state: () => ({
    // 购物车商品列表
    items: [],
    // 选中的商品ID列表
    selectedIds: [],
    // 购物车显示状态
    isVisible: false
  }),

  // 计算属性
  getters: {
    // 商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },

    // 选中的商品数量
    selectedCount: (state) => {
      return state.items.filter(item => 
        state.selectedIds.includes(item.id)
      ).reduce((total, item) => total + item.quantity, 0)
    },

    // 选中商品的总价
    selectedTotal: (state) => {
      return state.items
        .filter(item => state.selectedIds.includes(item.id))
        .reduce((total, item) => total + item.price * item.quantity, 0)
    },

    // 是否全选
    isAllSelected: (state) => {
      return state.items.length > 0 && 
             state.items.every(item => state.selectedIds.includes(item.id))
    }
  },

  // 操作方法
  actions: {
    // 添加商品到购物车
    addItem(product) {
      const existItem = this.items.find(item => item.id === product.id)
      if (existItem) {
        // 已存在则增加数量
        existItem.quantity += 1
      } else {
        // 限制购物车商品种类数量，例如最多50种
        if (this.items.length >= 50) {
          console.warn('购物车商品种类已达到上限')
          ElMessage.warning('购物车商品种类已达到上限')
          return
        }
        // 不存在则添加新商品
        this.items.push({
          id: product.id,
          name: product.name,
          price: product.price,
          image: product.image,
          quantity: 1,
          stock: product.stock
        })
      }
    },

    // 从购物车移除商品
    removeItem(productId) {
      const index = this.items.findIndex(item => item.id === productId)
      if (index > -1) {
        this.items.splice(index, 1)
        // 同时从选中列表中移除
        this.selectedIds = this.selectedIds.filter(id => id !== productId)
      }
    },

    // 更新商品数量
    updateQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId)
      if (item) {
        // 确保数量在合理范围内
        item.quantity = Math.max(1, Math.min(quantity, item.stock))
      }
    },

    // 选择商品
    toggleSelect(productId) {
      const index = this.selectedIds.indexOf(productId)
      if (index > -1) {
        this.selectedIds.splice(index, 1)
      } else {
        this.selectedIds.push(productId)
      }
    },

    // 全选/取消全选
    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedIds = []
      } else {
        this.selectedIds = this.items.map(item => item.id)
      }
    },

    // 清空购物车
    clearCart() {
      this.items = []
      this.selectedIds = []
    },

    // 显示/隐藏购物车
    toggleCartVisible() {
      this.isVisible = !this.isVisible
    }
  },

  // 持久化配置
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage,
        paths: ['items', 'selectedIds'] // 只持久化特定字段
      }
    ]
  }
})